package us.nchu.tomtiger.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import us.nchu.tomtiger.model.SmsVerifyCode;
import us.nchu.tomtiger.rowMapper.SmsVerifyCodeRowMapper;

import javax.annotation.Resource;


@Repository
public class SmsVerifyCodeDao {
    @Resource
    private JdbcTemplate jdbcTemplate;

    public SmsVerifyCodeDao(){
//		try {
//            //初始化查找命名空间
//            Context ctx = new InitialContext();
//            //参数java:/comp/env为固定路径
//            Context envContext = (Context)ctx.lookup("java:/comp/env");
//            //参数jdbc/mysqlds为数据源和JNDI绑定的名字
//            DataSource ds = (DataSource)envContext.lookup("jdbc/MySQL");
//            conn = ds.getConnection();
//
//        } catch (NamingException e) {
//            e.printStackTrace();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
    }

    public boolean insert(SmsVerifyCode verifyCode){
        String sql="insert into sms_verify_code(phone_number,code) values(?,?)";
//		PreparedStatement pstmt;
//		try {
//			pstmt=(PreparedStatement)conn.prepareStatement(sql);
//			pstmt.setString(1, verifyCode.getPhoneNumber());
//			pstmt.setString(2,verifyCode.getCode());
//
//			pstmt.executeUpdate();
//			pstmt.close();
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

        Object[] objects = new Object[]{verifyCode.getPhoneNumber(), verifyCode.getCode()};
        return jdbcTemplate.update(sql, objects) > 0;

    }

    public SmsVerifyCode query(String phoneNumber){
        SmsVerifyCode verifyCode = new SmsVerifyCode();
//
//		try {
//			Statement stmt=conn.createStatement();
//			ResultSet rs=stmt.executeQuery("select *  from sms_verify_code  where phone_number='"+phoneNumber+"'  order by _id desc");
//			while(rs!=null&&rs.next()){
//					verifyCode.setPhoneNumber(rs.getString(2));
//					verifyCode.setCode(rs.getString(3));
//					verifyCode.setTime(rs.getDate(4));
//					break;
//				}
//
//
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

        String sql = "select * from sms_verify_code where phone_number='"+phoneNumber+"' order by _id desc limit 1";
        verifyCode = (SmsVerifyCode)jdbcTemplate.queryForObject(sql, new SmsVerifyCodeRowMapper());

        return verifyCode;
    }

}
